package org.altervista.cp.microkernel.util;

import java.net.URL;

public final class ClassLoaderUtils {

	@SuppressWarnings("unchecked")
	public static <T> T getInstance(String className, T fallbackInstance) {
		try {
			return (T) Class.forName(className).newInstance();
		} catch (Exception e) {
			return fallbackInstance;
		}
	}

	public static URL lookupResource(String resourceName) {
		return lookupResource(resourceName, null);
	}

	public static URL lookupResource(String resourceName, Class<?> seeker) {
		URL resource = null;
		if (seeker != null) {
			resource = getClassLoader(seeker).getResource(resourceName);
		}
		if (resource == null) {
			resource = getClassLoader(ClassLoaderUtils.class).getResource(
					resourceName);
		}
		if (resource == null) {
			resource = Thread.currentThread().getContextClassLoader()
					.getResource(resourceName);
		}
		return resource;
	}

	public static ClassLoader getClassLoader(Class<?> c) {
		ClassLoader cl = c.getClassLoader();
		return cl == null ? ClassLoader.getSystemClassLoader() : cl;
	}
}
